package com.shwread.android.qysw.activity;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.dialog.DownloadDialog;
import com.shwread.android.ui.dialog.DownloadDialog.DownLoadDialogClickListener;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.http.base.EmptyHttpResponseHandler;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.IoTaskProgress;
import com.shwread.httpsdk.http.download.DownloadForProgressAction;
import com.tgx.tina.android.task.ATaskService;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import base.tina.core.task.infc.ITaskProgress.TaskProgressType;
import logic.bean.BookBean;
import logic.bean.BookInfo;
import logic.bean.DownLoadInfo;
import logic.bean.TOCItem;
import logic.beanenum.BookStatus_Enum;
import logic.beanenum.BookType_Enum;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.dao.BookDao;
import logic.util.FileUtil;
import logic.util.NetworkUtil;
import logic.util.PicassoUtil;
import logic.util.SDcardUtil;
import logic.util.Util;
import logic.util.logutil.LogUtil;
import logic.util.qryChapterInfoUtil;
import logic.xml.parser.NCXHandler;


/**
 * 书籍详情页面
 */
public class BookDetailActivity extends BaseBusinessActivity implements OnClickListener {
    /**
     * 记录当前书籍下载任务列表
     */
    private static HashMap<Integer, BookInfo> downloadMap = new HashMap<Integer, BookInfo>();
    private static final int MAX_DOWNLOAD_SIZE = 3;
    private static int notificationId = 0;
    private int currNotificationId;
    private static final int GET_CHAPTERLIST_OK = 100;
    private static final int GET_CHAPTERLIST_ERROE = GET_CHAPTERLIST_OK + 1;
    private static final int GET_CHAPTERINFO_OK = GET_CHAPTERLIST_ERROE + 1;
    private static final int GET_CHAPTERINFO_ERROR = GET_CHAPTERINFO_OK + 1;
    private static final int GET_BOOKINFO_OK = GET_CHAPTERINFO_ERROR + 1;
    private static final int GET_BOOKINFO_ERROR = GET_BOOKINFO_OK + 1;

    private TextView tvTitle, tvName, tvAuthor, tvClassify, tvStatus, tvRecommend, tvLongIntro;
    private View recommendView, body;
    private ImageView imgType;
    private ImageView imgCover;
    private Button btnBack;
    private TextView tvRead;
    private TextView tvDownload;
    private TextView tvTotalChapter;
    private LinearLayout llColumn;

    private BookInfo bean;
    private DownLoadInfo downInfo;
    private Context context;

    //	private WebImage                          webImage;
    private DownloadDialog dialog;
    private NotificationManager manager;
    private Notification notif;
    private PendingIntent pIntent;

    private List<TOCItem> catalogList;
    private BookDao bookMarkDao;
    //	private AddShelfBookAction  addShelfBookAction;

    private View loadingView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;
    private boolean isDownloadingCatalog = false;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_CHAPTERLIST_OK:
                    dialog.setMessage(bean.getName(), downInfo.getFileSize(), bean.getLogoUrl(), bean.getBookId());
                    dialog.show();
                    break;
                case GET_CHAPTERLIST_ERROE:
                    Util.showToast(context, "该书已下架");
                    break;
                case DefaultConsts.UPDATEUI_BOOKSHELF_BOOKS_OK:
                    onlineRead(bean.getContent_type());
                    //toReadingBookActivity(chapter_index);
                    break;
                case GET_BOOKINFO_OK:
                    setView();
                    downloadDirecoty(bean.getNcxUrl());
                    break;
                case GET_BOOKINFO_ERROR:
                    Util.showToast(context, "获取书籍信息失败");
                    break;
                default:
                    break;
            }
        }

    };
    /**
     * 是否已下载
     */
    private boolean isDown = false;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        bookMarkDao = BookDao.getInstance(this);
        if (getIntent().hasExtra("BookInfo")) {
            bean = (BookInfo) getIntent().getSerializableExtra("BookInfo");
        }
        if (bean == null) {
            Util.showToast(this, "书籍已下架");
            finish();
            return;
        } else if (Util.isEmpty(bean.getAuthor())) {
            showLoading();
//			new QryBookInfoByIdAction(context, bean.getBookId(), new BookInfoListener()).start();
            NewActionHelp.qryBookInfoById(context, bean.getBookId(), new BookInfoHandler());
        }
        if (getIntent().hasExtra(DefaultConsts.message_send_id)) {
            int msgViewId = getIntent().getIntExtra(DefaultConsts.message_send_id, -1);
//			new ReadMsgBySendIdAction(this, String.valueOf(msgViewId), new EmptyAction()).start();
            NewActionHelp.readMsgBySendId(this, String.valueOf(msgViewId), new EmptyHttpResponseHandler());
        }
        mAService = new ATaskService();
        mAService.startAService(context);

        //		addShelfBookAction = new AddShelfBookAction(this);
        findViews();
        updateLoadingView(1);
        setView();
        setListener();

        final String ncxPath = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + FileUtil.Book_CATALOGUE;
        if (!FileUtil.exists(ncxPath)) {
            downloadDirecoty(bean.getNcxUrl());
        } else {
            initDirctory(BookStatus_Enum.ONLINE.getValue());
            tvTotalChapter.setText(getResources().getString(R.string.chapter_total, bean.getTotalChapters()));
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (!existMainActivity()) {
            startActivity(new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP));
        }
    }

    @Override
    protected void onPause() {
        //closeLoading();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (mAService != null) {
            mAService.stopAService();
        }
        super.onDestroy();
    }

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    private void findViews() {
        setContentView(R.layout.book_detail);
        tvTitle = (TextView) findViewById(R.id.book_detail_header_name);
        btnBack = (Button) findViewById(R.id.book_detail_header_back);
        btnBack.setOnClickListener(this);

        body = findViewById(R.id.book_detail_body);
        tvName = (TextView) findViewById(R.id.book_detail_name);
        tvAuthor = (TextView) findViewById(R.id.book_detail_author);
        tvClassify = (TextView) findViewById(R.id.book_detail_classify);
        tvStatus = (TextView) findViewById(R.id.book_detail_status);
        recommendView = findViewById(R.id.book_detail_recommend_layout);
        tvRecommend = (TextView) findViewById(R.id.book_detail_recommend);
        tvLongIntro = (TextView) findViewById(R.id.book_detail_long_intro);
        imgCover = (ImageView) findViewById(R.id.book_detail_cover);
        imgType = (ImageView) findViewById(R.id.book_detail_type);
        tvRead = (TextView) findViewById(R.id.book_detail_will_read);
        tvRead.setOnClickListener(this);
        tvDownload = (TextView) findViewById(R.id.book_detail_download);
        tvDownload.setOnClickListener(this);
        llColumn = (LinearLayout) findViewById(R.id.book_detail_column);
        llColumn.setOnClickListener(this);
        tvTotalChapter = (TextView) findViewById(R.id.directory_total_num_tv);

        loadingView = findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) findViewById(R.id.common_loading__img);
        if (bean.getContent_type() != null && bean.getBookType() != null) {
            if (bean.getContent_type().equals("2") && bean.getBookType().equals("2"))
                tvDownload.setVisibility(View.GONE);
        }
        dialog = new DownloadDialog(context);
    }

    private void setView() {
        setBookTypeIcon(imgType, bean.getContent_type());

        //		tvTitle.setText(bean.getName());
        tvTitle.setText("书籍详情");
        tvName.setText(bean.getName());
//		imgCover.setImageUrl(bean.getLogoUrl());
        PicassoUtil.load(BookDetailActivity.this, bean.getLogoUrl(), R.drawable.bookcover_default, imgCover);
        tvAuthor.setText("作者：" + bean.getAuthor());
        tvClassify.setText("分类：" + bean.getFirstSortName());
        final String isFinished = bean.getIsFinished();
        if (!TextUtils.isEmpty(isFinished)) {
            tvStatus.setText(isFinished.toLowerCase().equals("y") ? "状态：已完结" : "状态：未完结");
        }
        if (TextUtils.isEmpty(bean.getEditorRecommend())) {
            recommendView.setVisibility(View.GONE);
        } else {
            recommendView.setVisibility(View.VISIBLE);
            tvRecommend.setText(bean.getEditorRecommend());
        }
        tvLongIntro.setText(bean.getLongIntro());

        final String tempPath = FileUtil.DownloadPath() + bean.getBookId() + ".ceb";
        if (FileUtil.exists(tempPath)) {
            tvDownload.setText("已下载");
            //			tvDownload.setEnabled(false);
            isDown = true;
        }

        if (bean.getContent_type() != null && bean.getBookType() != null) {
            if (bean.getContent_type().equals("2") && bean.getBookType().equals("2"))
                tvDownload.setVisibility(View.GONE);
        }
    }

    void setListener() {
        dialog.setPageListener(new DownLoadDialogClickListener() {

            @Override
            public void okListener(View v) {
                dialog.dismiss();
                downloadBook();
            }

            @Override
            public void cancelListener(View v) {
                dialog.dismiss();
            }
        });
    }

    void addBooktoShelf(int status, int chapterIndex) {
        bookMarkDao.addBooktoShelf(toBookBean(status, chapterIndex, bean));
        onlineRead(bean.getContent_type());
    }

    private BookBean toBookBean(int status, int chapterIndex, BookInfo bean) {
        String path = "";
        if (status == BookStatus_Enum.DOWNLOAD.getValue()) {
            path = FileUtil.DownloadPath() + String.valueOf(bean.getBookId()) + ".ceb";
        } else if (status == BookStatus_Enum.ONLINE.getValue()) {
            path = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + "toc.ncx";
        }
        if ("1".equals(bean.getBookType())) {
            bean.setContent_type("6");
        }
        BookBean bookbean = new BookBean(status, bean.getBookId(), bean.getName(), Integer.parseInt(bean.getContent_type()), chapterIndex, path, bean.getAuthor(), Const.phone_number, String.valueOf(System.currentTimeMillis()), bean.getLogoUrl());
        return bookbean;
    }

    /**
     * @param @param index 设定文件
     * @return void 返回类型
     * @throws
     * @Title: readTextBook
     * @Description: 跳转阅读页面
     */
    void readTextBook(int index) {
        Intent intent = new Intent(context, ReadingBookActivity.class);
        intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.getBookId()));
        intent.putExtra(DefaultConsts.chapterId_index_i, index);
        intent.putExtra(DefaultConsts.book_name, bean.getName());
        String path = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + "toc.ncx";
        Uri url = Uri.parse(path);
        intent.setData(url);
        intent.putExtra(ReadingBookActivity.BOOKSTATUS, BookStatus_Enum.ONLINE.getValue());
        startActivity(intent);
        if ((chapter_index < catalogList.size() - 1) && !FileUtil.FileExist(String.valueOf(bean.getBookId()), catalogList.get(chapter_index + 1).getId() + ".html")) {
//			new QryChapterInfoAction(context, String.valueOf(bean.getBookId()), catalogList.get(index + 1).getId(), null).start();
            new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bean.getBookId()), catalogList.get(index + 1).getId());

        }
    }

    void readMagazineBook() {

        BookBean bookbean = toBookBean(BookStatus_Enum.ONLINE.getValue(), chapter_index, bean);

        Intent intent = new Intent(this, ReadingmagazineActivity.class);
//		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("BookMarkBean", bookbean);
        intent.putExtra(DefaultConsts.chapterId_index_i, chapter_index);
        startActivity(intent);
        if ((chapter_index < catalogList.size() - 1) && !FileUtil.FileExist(String.valueOf(bean.getBookId()), catalogList.get(chapter_index + 1).getId() + ".html")) {
//			new QryChapterInfoAction(context, String.valueOf(bean.getBookId()), catalogList.get(chapter_index + 1).getId(), null).start();
            new qryChapterInfoUtil().qryChapterInfo(context, String.valueOf(bean.getBookId()), catalogList.get(chapter_index + 1).getId());

        }
    }

    /**
     * @return void 返回类型
     * @throws
     * @Title: goCatalogActivity
     * @Description: 跳转目录页面
     */
    public void goCatalogActivity() {
        Intent intent = new Intent(this, CatalogActivity.class);
        intent.putExtra("BookInfo", bean);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.book_detail_header_back:
                onBackPressed();
                break;
            case R.id.book_detail_will_read:
                if (!SDcardUtil.isSDCARDMounted()) {
                    Util.showToast(this, getResources().getString(R.string.image_save_sdcard_deny));
                    return;
                }
                if (Util.isEmpty(bean.getContent_type())) {
                    Util.showToast(context, "服务器数据返回错误");
                    return;
                }

                if (isDownloadingCatalog) {
                    Util.showToast(context, "正在下载目录，请稍等");
                    return;
                }

                if (isDown) {
                    System.out.println("离线阅读");
                    readDownloadBook();
                } else {
                    System.out.println("在线阅读");
                    if (NetworkUtil.isNetAvailable(context)) {
                        readBook();
                    } else {
                        new NoNetDialog(context).show();
                    }
                }
                break;
            case R.id.book_detail_download:
                if (!SDcardUtil.isSDCARDMounted()) {
                    Util.showToast(this, getResources().getString(R.string.image_save_sdcard_deny));
                    return;
                }
                if (Util.isEmpty(bean.getContent_type())) {
                    Util.showToast(context, "服务器数据返回错误");
                    return;
                }
                if (!NetworkUtil.isNetAvailable(context) && !isDown) {
                    new NoNetDialog(context).show();
                } else {
                    final String str = tvDownload.getText().toString();
                    if (str.equals("已下载")) {
                        Util.showToast(context, "下载完成，可在" + getResources().getString(R.string.maintab_bookshelf) + "查看");
                    } else if (str.equals("下载")) {
                        getDownloadInfo();
                    } else {
                        Util.showToast(context, "正在下载");
                    }
                }

                break;
            case R.id.book_detail_column:
                if (NetworkUtil.isNetAvailable(context)) {
                    goCatalogActivity();
                } else {
                    new NoNetDialog(context).show();
                }
                break;
            default:
                break;
        }
    }

    void readDownloadBook() {
        chapter_index = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getChapterIndex(String.valueOf(bean.getBookId()));
        bookMarkDao.addBooktoShelf(toBookBean(BookStatus_Enum.DOWNLOAD.getValue(), chapter_index, bean));

        int index = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getLocalIndex(String.valueOf(bean.getBookId()));
        Intent intent = new Intent(this, ReadingBookActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(ReadingBookActivity.BOOKSTATUS, BookStatus_Enum.DOWNLOAD.getValue());
        intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.getBookId()));
        intent.putExtra(DefaultConsts.chapterId_index_i, index);
        intent.putExtra(DefaultConsts.book_name, bean.getName());
        String urlpath = FileUtil.DownloadPath() + String.valueOf(bean.getBookId()) + ".ceb"; //"/oebps"
        Uri url = Uri.parse(urlpath);
        intent.setData(url);
        startActivity(intent);
    }

    void onlineRead(String type) {
        if (null == bean || null == catalogList) {
            //closeLoading();
            Util.showToast(context, "该书已下架");
            return;
        }

        if (type.equals(BookType_Enum.BOOK.getValue())) {
            readTextBook(chapter_index);
        } else if (type.equals(BookType_Enum.MAGAZINE.getValue())) {
            readMagazineBook();
        } else if (type.equals(BookType_Enum.SERIAL.getValue())) {
            readTextBook(chapter_index);
        } else if (type.equals(BookType_Enum.UMD.getValue())) {
            Util.showToast(context, "暂时不支持漫画格式书籍阅读");
        } else if (type.equals(BookType_Enum.TEXT.getValue())) {
            readTextBook(chapter_index);
        } else if (type.equals(BookType_Enum.LISTEN.getValue())) {
            Util.showToast(context, "暂时不支持听书");
        } else {
            Util.showToast(context, "无法识别的书籍类型");
        }

    }

    private int chapter_index = 0;

    /**
     * 是否第一次阅读书籍
     */
    void readBook() {
        //showLoading();
        if (catalogList == null) {
            Util.showToast(context, "此书无目录数据，无法阅读");
            return;
        }
        chapter_index = QyreaderPerferencesUtil.getInstance(context, Const.phone_number).getChapterIndex(String.valueOf(bean.getBookId()));
        addBooktoShelf(BookStatus_Enum.ONLINE.getValue(), chapter_index);
        onlineRead(bean.getContent_type());
    }

    /**
     * @return void 返回类型
     * @throws
     * @Title: downloadBook
     * @Description: 下载书籍
     */
    void downloadBook() {
        if (downloadMap.size() > MAX_DOWNLOAD_SIZE) {
            Util.showToast(context, "最多同时下载" + MAX_DOWNLOAD_SIZE + "本书籍");
        } else {
            ++notificationId;
            currNotificationId = notificationId;
            downloadMap.put(currNotificationId, bean);
            manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notif = new Notification();
            notif.icon = R.drawable.bookcover_default;
            notif.flags = Notification.FLAG_ONLY_ALERT_ONCE;
            notif.tickerText = "下载";
            // 通知栏显示所用到的布局文件

            notif.contentView = new RemoteViews(getPackageName(), R.layout.notice_dialog_lay);
            notif.contentView.setTextViewText(R.id.mobile_kan_dian, bean.getName());
            notif.contentView.setImageViewResource(R.id.content_view_image, R.drawable.ic_launcher);
            notif.contentIntent = getPendingIntent(true);

            manager.notify(notificationId, notif);
            BaseSimpleActivity.notificationMap.put(notificationId, DefaultConsts.DOWNLOAD_NOTIFICATION_FLAG);
            new DownloadForProgressAction(context, downInfo.getUrl(), FileUtil.DownloadPath() + bean.getBookId() + ".ceb", new DownBookProgress(notificationId)).start();
        }
    }

    private PendingIntent getPendingIntent(boolean isEmpty) {
        //通知栏点击事件
        if (isEmpty) {
            pIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
        } else {
            Intent intent = new Intent();
            intent.setClass(context, ReadingBookActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            String urlpath = "";
            int index = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getLocalIndex(String.valueOf(bean.getBookId()));
            urlpath = FileUtil.DownloadPath() + bean.getBookId();
            urlpath = urlpath + "/" + "oebps";
            Uri bookurl = Uri.parse(urlpath);
            intent.setData(bookurl);
            intent.putExtra(ReadingBookActivity.BOOKSTATUS, 3);
            intent.putExtra(DefaultConsts.book_contentId_s, String.valueOf(bean.getBookId()));
            intent.putExtra(DefaultConsts.book_name, bean.getName());
            intent.putExtra(DefaultConsts.chapterId_index_i, index);
            intent.setAction(ReadingBookActivity.SHOW_CATALOG);
            pIntent = PendingIntent.getActivity(context, 0, intent, 0);
        }
        return pIntent;
    }

//	private Bitmap getBitmap(String url) {
//		Util.loadImg();
//		webImage = new WebImage(url);
//		return webImage.getBitmap(this);
//	}

    TaskProgressType taskType;
    long progressIncress = 0;
    long progressMax = 0;

    /**
     * @Project： Lqyd_Android
     * @Title：DownBookProgress
     * @Description：下载进度条
     * @Author：wayne
     * @Date：2014年8月26日下午5:02:02
     */
    class DownBookProgress
            implements
            IoTaskProgress {
        private int id;

        public DownBookProgress(int id) {
            super();
            this.id = id;
        }

        @Override
        public void createProgress(HttpType httpType, TaskProgressType type, long max) {

        }

        @Override
        public void updateProgress(HttpType httpType, TaskProgressType type, long increase, long max) {
            progressIncress = increase;
            progressMax = max;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    notif.contentView.setTextViewText(R.id.content_view_text1, Util.getPercent(progressIncress, progressMax, 0) + "%");
                    tvDownload.setText("下载" + " " + Util.getPercent(progressIncress, progressMax, 0) + "%");
                    //					tvDownload.setEnabled(false);
                    notif.contentView.setProgressBar(R.id.ProgressBar_myStyle, 100, Integer.valueOf(Util.getPercent(progressIncress, progressMax, 0)), false);
                    manager.notify(id, notif);
                }
            });

        }

        @Override
        public void finishProgress(HttpType httpType, TaskProgressType type) {
            taskType = type;
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (taskType.name().equals("complete")) {
                        LogUtil.d("hss", "下载书籍完成了");
                        if (id == currNotificationId) {
                            tvDownload.setText("已下载");
                            //							tvDownload.setEnabled(false);
                            isDown = true;
                        }

                        notif.contentView.setProgressBar(R.id.ProgressBar_myStyle, 100, 100, false);
                        notif.contentView.setTextViewText(R.id.content_view_text1, "下载完成");
                        notif.contentIntent = getPendingIntent(false);
                        notif.flags |= Notification.FLAG_AUTO_CANCEL;

                        //解压ceb 文件
                        if ("101".equals(bean.getDownType())) {
                            bookMarkDao.addBooktoShelf(toBookBean(BookStatus_Enum.DOWNLOAD.getValue(), 0, bean));
                        }

                        manager.notify(id, notif);
                    } else if (taskType.name().equals("cancle") || taskType.name().equals("error")) {
                        if (id == currNotificationId) {
                            tvDownload.setText("下载");
                            //							tvDownload.setEnabled(true);
                        }
                        isDown = false;
                        /* 下载失败，删除文件 */
                        FileUtil.delFile(FileUtil.DownloadPath() + bean.getBookId() + ".ceb");
                        notif.contentView.setTextViewText(R.id.content_view_text1, "下载失败");
                        manager.notify(id, notif);
                    }
                    downloadMap.remove(id);
                }
            });

        }

    }

    /**
     * @param @param url 设定文件
     * @return void 返回类型
     * @throws
     * @Title: downloadDirecoty
     * @Description: 下载目录
     */
    void downloadDirecoty(String url) {
        new DownloadForProgressAction(this, url, FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + FileUtil.Book_CATALOGUE, new DirecotryProgress()).start();
        isDownloadingCatalog = true;
    }

    class DirecotryProgress
            implements
            IoTaskProgress {

        @Override
        public void createProgress(HttpType httpType, TaskProgressType type, long max) {

        }

        @Override
        public void updateProgress(HttpType httpType, TaskProgressType type, long increase, long max) {

        }

        @Override
        public void finishProgress(HttpType httpType, TaskProgressType type) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    //					updateLoadingView(1);
                    //					Util.showToast(context, "目录已下载完成");
                    tvTotalChapter.setText(getResources().getString(R.string.chapter_total, bean.getTotalChapters()));
                    initDirctory(BookStatus_Enum.ONLINE.getValue());
                    isDownloadingCatalog = false;
                }
            });
        }

    }

    /**
     * @return void 返回类型
     * @throws
     * @Title: getDownloadInfo
     * @Description: 获取文件下载内容
     */
    private void getDownloadInfo() {
//		new DownLoadContentAction(this, bean.getBookId(), bean.getDownType(), new DownListener()).start();
        NewActionHelp.downLoadContent(this, bean.getBookId(), bean.getDownType(), new DownHandler());
    }

    private class DownHandler extends ObjectHttpResponseHandler<DownLoadInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Util.showToast(context, "目前暂时无法下载，请稍后再试");
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, DownLoadInfo object, String responseString) {
            if (object != null) {
                downInfo = object;
                handler.sendEmptyMessage(GET_CHAPTERLIST_OK);
            } else {
                Util.showToast(context, "书籍下载信息为空，无法下载！");
            }

        }

        @Override
        public Type getType() {
            return new TypeToken<DownLoadInfo>() {
            }.getType();
        }

    }


    class DownListener
            implements
            ActionListener {

        @Override
        public void OK(Object obj) {
            if (obj != null) {
                downInfo = (DownLoadInfo) obj;
                handler.sendEmptyMessage(GET_CHAPTERLIST_OK);
            } else {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Util.showToast(context, "书籍下载信息为空，无法下载！");
                    }
                });
            }
        }

        @Override
        public void ERROR(int resultCode, String message) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Util.showToast(context, "目前暂时无法下载，请稍后再试");
                }
            });
        }

        @Override
        public void HTTPERROR(int statusCode) {

        }

    }

    private void initDirctory(int status) {
        String dirctory = "";
        if (status == BookStatus_Enum.ONLINE.getValue()) {

            dirctory = FileUtil.OnlinePath(String.valueOf(bean.getBookId())) + FileUtil.Book_CATALOGUE;
        } else if (status == BookStatus_Enum.LOCAL.getValue()) {
            dirctory = FileUtil.DownloadPath() + bean.getBookId() + "/META-INF/book.ncx";
        }
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser;
        try {
            parser = factory.newSAXParser();
            InputStream is = new FileInputStream(new File(dirctory));
            NCXHandler handle = new NCXHandler();
            parser.parse(is, handle);
            is.close();
            if (null != catalogList && catalogList.size() > 0) catalogList.removeAll(catalogList);
            catalogList = handle.getNavPointList();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                body.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                body.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                body.setVisibility(View.VISIBLE);
                break;
        }
    }

    private class BookInfoHandler extends ObjectHttpResponseHandler<BookInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            closeLoading();
            if (statusCode > 1000) {
                handler.sendEmptyMessage(GET_BOOKINFO_ERROR);
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, BookInfo object, String responseString) {
            bean = object;
            closeLoading();
            handler.sendEmptyMessage(GET_BOOKINFO_OK);

        }

        @Override
        public Type getType() {
            return new TypeToken<BookInfo>() {
            }.getType();
        }

    }


    class BookInfoListener
            implements
            ActionListener {

        @Override
        public void OK(Object obj) {
            bean = (BookInfo) obj;
            closeLoading();
            handler.sendEmptyMessage(GET_BOOKINFO_OK);
        }

        @Override
        public void ERROR(int resultCode, String message) {
            closeLoading();
            handler.sendEmptyMessage(GET_BOOKINFO_ERROR);
        }

        @Override
        public void HTTPERROR(int statusCode) {
            closeLoading();
        }

    }
}
